<template>
  <div style="height: 80%">
    <div class="table-box table-content">
      <ProTable
        ref="cabProTable"
        :columns="columns"
        :request-api="getChangeCommitteeList"
        :init-param="initParam"
        :request-auto="true"
        :data-callback="dataCallback"
        @row-click="showCabMemberList"
        :search-col="{ xs: 1, sm: 1, md: 1, lg: 1, xl: 1 }"
        row-key="cabId"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader="scope">
          <el-button type="primary" :icon="CirclePlus" @click="addCab">新增</el-button>
          <el-button type="primary" :icon="EditPen" plain @click="editCab(scope)">编辑</el-button>
          <el-button type="primary" :icon="Delete" plain @click="delCab(scope)">删除</el-button>
        </template>
      </ProTable>

      <el-drawer v-model="cabDrawer" :title="`${cabTitle}变更委员会`" :direction="direction" :before-close="handleClose">
        <el-form>
          <el-form-item label="名称">
            <el-input v-model="cabName" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="cabDesc" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="操作">
            <el-button type="primary" :icon="Upload" @click="UploadCab">提交</el-button>
          </el-form-item>
        </el-form>
      </el-drawer>
    </div>
    <div class="table-box table-content">
      <ProTable
        ref="cabMemberProTable"
        :columns="cabMemberColumns"
        :request-api="getChangeCommitteeMemberList"
        :init-param="ChangeCommitteeMemberInitParam"
        :request-auto="false"
        :data-callback="cabMemberCallback"
        :search-col="{ xs: 1, sm: 1, md: 1, lg: 1, xl: 1 }"
        row-key="cabMemberId"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader="scope">
          <el-button type="primary" :icon="CirclePlus" @click="addCabMember">新增</el-button>
          <el-button type="primary" :icon="EditPen" plain @click="editCabMember(scope)">编辑</el-button>
          <el-button type="primary" :icon="Delete" plain @click="delCabMember(scope)">删除</el-button>
        </template>
      </ProTable>

      <el-drawer
        v-model="cabMemberDrawer"
        :title="`${cabMemberTitle}委员会成员`"
        :direction="direction"
        :before-close="handleClose"
      >
        <el-form>
          <el-form-item label="审批委员">
            <el-input v-model="cabMemberName" placeholder="请输入内容" @click="getUser" />
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="cabMemberDesc" placeholder="请输入内容" />
          </el-form-item>
          <el-form-item label="操作">
            <el-button type="primary" :icon="Upload" @click="UploadCabMember">提交</el-button>
          </el-form-item>
        </el-form>
      </el-drawer>
      <el-dialog v-model="dialogVisible" title="选择用户" width="80%" :before-close="handleClose_getUser">
        <div class="main-box">
          <TreeFilter
            label="data"
            id="attr"
            title="部门列表"
            :data="treeFilterData"
            :default-value="treeInitParam.departmentId"
            @change="changeTreeFilter"
          />
          <div style="height: auto" class="table-box">
            <ProTable
              ref="useProTable"
              :columns="userColumns"
              :request-api="getUserTreeList"
              :init-param="treeInitParam"
              :request-auto="true"
              :data-callback="dataCallback"
              :search-col="{ xs: 1, sm: 1, md: 1, lg: 1, xl: 1 }"
            >
              <template #operation="scope">
                <el-button type="primary" :icon="Select" @click="chooseUser(scope)">选择</el-button>
              </template>
            </ProTable>
          </div>
        </div>
        <!-- <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="dialogVisible = false">确认</el-button>
          </span>
        </template> -->
      </el-dialog>
    </div>
  </div>
</template>
<script setup lang="ts" name="changeCommittee">
import { ref, reactive, onMounted } from "vue";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import {
  getChangeCommitteeList,
  checkChangeCommittee,
  addChangeCommittee,
  checkChangeCommitteeEdit,
  editChangeCommittee,
  delChangeCommittee,
  getChangeCommitteeMemberList,
  addChangeCommitteeMember,
  editChangeCommitteeMember,
  delChangeCommitteeMember
} from "@/api/modules/dataDictionary";
import {
  CirclePlus,
  Delete,
  EditPen,
  Select,
  Search,
  Download,
  Upload,
  View,
  Refresh,
  InfoFilled
} from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import type { DrawerProps } from "element-plus";
import TreeFilter from "@/components/TreeFilter/treeFilter.vue";
import { getUserDepartment, getUserTreeList } from "@/api/modules/user";
const cabProTable = ref<ProTableInstance>();
const cabMemberProTable = ref<ProTableInstance>();
const columns = reactive<ColumnProps<any>[]>([
  { type: "selection" },
  {
    prop: "cabId",
    label: "编号",
    sortable: true
  },
  {
    prop: "cabName",
    label: "名称",
    sortable: true,
    search: {
      el: "input",
      tooltip: "输入自定义类型名称",
      label: "输入名称",
      key: "cabQueryDto.cabName"
    }
  },
  {
    prop: "cabDesc",
    label: "描述",
    sortable: true
  }
]);
const cabMemberColumns = reactive<ColumnProps<any>[]>([
  { type: "selection" },
  {
    prop: "cabMemberId",
    label: "编号",
    sortable: true
  },
  {
    prop: "approvalMemberFullName",
    label: "变更委员",
    sortable: true
  },
  {
    prop: "desc",
    label: "描述",
    sortable: true
  }
]);
const initParam = ref("");
const ChangeCommitteeMemberInitParam = reactive({ cabId: "" });
const cabDrawer = ref(false);
const cabMemberDrawer = ref(false);
const direction = ref<DrawerProps["direction"]>("rtl");
const cabTitle = ref("");
const cabName = ref("");
const cabDesc = ref("");
const cabMemberName = ref("");
const cabMemberDesc = ref("");
const cabMemberTitle = ref("");

const dialogVisible = ref(false);
const treeFilterData = ref<any>([]);
const treeInitParam = reactive({
  departmentId: ""
});
const userId = ref("");
const userColumns = reactive<ColumnProps<any>[]>([
  { type: "selection" },
  {
    prop: "loginName",
    label: "登录名",
    sortable: true,
    search: {
      el: "input",
      tooltip: "输入级别名称",
      label: "输入名称",
      key: "updateLevelQueryDTO.ulName"
    }
  },
  {
    prop: "fullName",
    label: "名字",
    sortable: true
  },
  {
    prop: "email",
    label: "邮件",
    sortable: true
  },
  {
    prop: "holidayStatus",
    label: "休假状态",
    sortable: true,
    render: (scope: any) => {
      switch (scope.row.holidayStatus) {
        case true:
          return "休假";
        case false:
          return "值班中";
        default:
          return "";
      }
    }
  },
  { prop: "operation", label: "操作" }
]);
//获取用户
const getUser = async e => {
  console.log(e);
  dialogVisible.value = true;
  const data = await getUserDepartment();
  treeFilterData.value = data;
  treeInitParam.departmentId = treeFilterData.value[0].attr.orgNo;
};
//弹出框操作
const handleClose_getUser = (done: () => void) => {
  ElMessageBox.confirm("确定退出吗?")
    .then(() => {
      done();
    })
    .catch(() => {
      // catch error
    });
};
//选择用户
const chooseUser = e => {
  console.log(e);
  cabMemberName.value = e.row.fullName;
  dialogVisible.value = false;
  userId.value = e.row.userId;
};
const changeTreeFilter = (e: any) => {
  if ((e as any).id.orgNo === "1") {
    treeInitParam.departmentId = "";
  } else {
    treeInitParam.departmentId = (e as any).id.orgNo;
  }
};
const dataCallback = (data: any) => {
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};
const cabMemberCallback = (data: any) => {
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};
//新增变更审批委员会列表
const addCab = () => {
  cabDrawer.value = true;
  cabTitle.value = "新增";
};
const cabId = ref("");
const editCab = e => {
  console.log(e.selectedList);
  if (e.selectedList.length > 1 || e.selectedList.length === 0) {
    ElMessage.error("请选择一条数据");
    return;
  } else {
    ElMessage.success("编辑");
    cabDrawer.value = true;
    cabTitle.value = "编辑";
    cabName.value = e.selectedList[0].cabName;
    cabDesc.value = e.selectedList[0].cabDesc;
    cabId.value = e.selectedList[0].cabId;
  }
};
const delCab = async scope => {
  if (scope.selectedList.length === 0) {
    ElMessage.error("请选择至少一条数据");
  } else {
    let delStr = "";
    scope.selectedList.forEach(item => {
      delStr += item.cabName + ",";
    });
    ElMessageBox.confirm("您确定要删除这些:" + delStr + "数据吗", "删除确认", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
      center: true
    })
      .then(async () => {
        let params = "";
        scope.selectedList.forEach(item => {
          params += "cabIds=" + item.cabId + "&";
        });
        const data = await delChangeCommittee(params);
        try {
          if ((data as any) === null) {
            cabDrawer.value = false;
            cabDesc.value = "";
            cabName.value = "";
            cabProTable.value?.clearSelection();
            cabProTable.value?.getTableList();
          }
        } catch {
          ElMessage.error("此数据存在相关联的数据，不能删除");
        }
        ElMessage({
          type: "success",
          message: "删除成功"
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除"
        });
      });
  }
};
//
const handleClose = () => {
  //
  cabDrawer.value = false;
  cabName.value = "";
  cabDesc.value = "";
  cabId.value = "";
  //
  cabMemberDrawer.value = false;
  cabMemberTitle.value = "";
  cabMemberName.value = "";
};
//提交变更审批委员会
const UploadCab = async () => {
  if (cabTitle.value === "新增") {
    const checkParams = {
      "cabDto.cabName": cabName.value
    };
    const res = await checkChangeCommittee(checkParams);
    if ((res as any) === "") {
      const params = {
        "cabDto.cabId": "",
        "cabDto.cabName": cabName.value,
        "cabDto.cabDesc": cabDesc.value
      };
      const data = await addChangeCommittee(params);
      if ((data as any) === null) {
        ElMessage.success("新增成功");
        cabName.value = "";
        cabDesc.value = "";
        cabDrawer.value = false;
        cabProTable.value?.getTableList();
      }
    }
  } else if (cabTitle.value === "编辑") {
    const checkParams = {
      " cabDto.cabName": cabName.value,
      "cabDto.cabId": cabId.value
    };
    const res = await checkChangeCommitteeEdit(checkParams);
    if ((res as any) === "") {
      const params = {
        "cabDto.cabId": cabId.value,
        "cabDto.cabName": cabName.value,
        "cabDto.cabDesc": cabDesc.value
      };
      const data = await editChangeCommittee(params);
      if ((data as any) === null) {
        ElMessage.success("编辑成功");
        cabName.value = "";
        cabDesc.value = "";
        cabDrawer.value = false;
        cabProTable.value?.getTableList();
      }
    }
  }
};
//
const isAddVisitItem = ref(true);
const showCabMemberList = e => {
  // console.log(e);
  ChangeCommitteeMemberInitParam["cabId"] = e.cabId;
};
//添加变更委员会成员
const addCabMember = e => {
  if (ChangeCommitteeMemberInitParam.cabId === "") {
    ElMessage.error("请先选择一个变更审批委员会再操作");
  } else {
    if (isAddVisitItem.value === true) {
      cabMemberDrawer.value = true;
      cabMemberTitle.value = "新增";
    } else {
      ElMessage.error("当前类型不需要填写选项值！");
    }
  }
};
//编辑变更委员会成员
const cabMemberId = ref("");
const editCabMember = e => {
  console.log(e.selectedList);
  if (e.selectedList.length > 1 || e.selectedList.length === 0) {
    ElMessage.error("请选择一条数据");
    return;
  } else {
    ElMessage.success("编辑");
    cabMemberDrawer.value = true;
    cabMemberTitle.value = "编辑";
    cabMemberName.value = e.selectedList[0].approvalMemberFullName;
    cabMemberDesc.value = e.selectedList[0].desc;
    cabMemberId.value = e.selectedList[0].cabMemberId;
  }
};
//删除变更委员会成员
const delCabMember = async scope => {
  if (scope.selectedList.length === 0) {
    ElMessage.error("请选择至少一条数据");
  } else {
    let delStr = "";
    scope.selectedList.forEach(item => {
      delStr += item.approvalMemberFullName + ",";
    });
    ElMessageBox.confirm("您确定要删除这些:" + delStr + "数据吗", "删除确认", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
      center: true
    })
      .then(async () => {
        let params = "";
        scope.selectedList.forEach(item => {
          console.log(item);
          params += "cabMemberIds=" + item.cabMemberId + "&";
        });
        const data = await delChangeCommitteeMember(params + "&cabId=" + ChangeCommitteeMemberInitParam["cabId"]);
        try {
          if ((data as any) === null) {
            cabMemberDrawer.value = false;
            cabMemberName.value = "";
            cabMemberDesc.value = "";
            cabMemberProTable.value?.clearSelection();
            cabMemberProTable.value?.getTableList();
          }
        } catch {
          ElMessage.error("此数据存在相关联的数据，不能删除");
        }
        ElMessage({
          type: "success",
          message: "删除成功"
        });
      })
      .catch(() => {
        ElMessage({
          type: "info",
          message: "取消删除"
        });
      });
  }
};
//提交变更委员会成员
const UploadCabMember = async e => {
  if (cabMemberTitle.value === "新增") {
    const params = {
      "cabMemberDto.cabId": ChangeCommitteeMemberInitParam.cabId,
      "cabMemberDto.cabMemberId": "",
      "cabMemberDto.approvalMember": userId.value,
      "cabMemberDto.desc": cabMemberDesc.value
    };
    const data = await addChangeCommitteeMember(params);
    console.log(data);
    if ((data as any) === null) {
      ElMessage.success("新增成功");
      cabMemberDrawer.value = false;
      cabMemberName.value = "";
      cabMemberDesc.value = "";
      cabMemberProTable.value?.getTableList();
    }
  } else if (cabMemberTitle.value === "编辑") {
    const params = {
      "cabMemberDto.cabId": ChangeCommitteeMemberInitParam.cabId,
      "cabMemberDto.cabMemberId": cabMemberId.value,
      "cabMemberDto.approvalMember": userId.value,
      "cabMemberDto.desc": cabMemberDesc.value
    };
    const data = await editChangeCommitteeMember(params);
    if ((data as any) === null) {
      ElMessage.success("编辑成功");
      cabMemberDrawer.value = false;
      cabMemberName.value = "";
      cabMemberDesc.value = "";
      cabMemberProTable.value?.getTableList();
    }
  }
};
</script>
